﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Go.Model
{
    public class BuilderGame
    {
        private LinkedList<Player> _players;
        private int _sizeBoard;
        private static BuilderGame _instance=null;

        public static BuilderGame instance() {
            if (_instance == null)
                _instance = new BuilderGame();
            return _instance;
        }
        private BuilderGame() {
            _players = new LinkedList<Player>();
            _sizeBoard = 0;
        }

        public static void reset() {
            _instance = null;
        }

        public int SizeBoard
        {
            get { return _sizeBoard; }
            set { _sizeBoard = value; }
        }

        public void addPlayer( Player player)
        {
            validateAddPlayer(player);
            if (player.isWhite() )
               _players.AddFirst(player);
            else
               _players.AddLast(player);
        }

        private void validateAddPlayer(Player player)
        {
            foreach (Player aPlayer in _players)
            {
                if (aPlayer.Color == player.Color)
                {
                    throw new System.ArgumentException("Error, no se puede ingresar 2 jugadores con el mismo color");
                }
            }
            if (_players.Count > 2)
                throw new System.ArgumentException("Error, no se puede ingresar mas de 2 jugadores");
        }

        private void validateBuild()
        {
            if (_players.Count != 2)
                throw new System.ArgumentException("Error, no se puede crear un juego si no se ingresaron 2 jugadores");
            if (_sizeBoard == 0)
                throw new System.ArgumentException("Error, no se ingreso un tamaño de tablero");
            
        }

        public void setOponent(){
            _players.First().Opponent=_players.Last();
            _players.Last().Opponent=_players.First();
        }

        public Player getWhitePlayer()
        {
            foreach (Player aPlayer in _players)
            {
                if (aPlayer.isWhite())
                    return aPlayer;
            }
            throw new System.ArgumentException("Error, no hay ningun jugador que juegue con blancas");
        }

        public Game build() {
            validateBuild();
            BoardFactory.createBoard(_sizeBoard);
            this.setOponent();
            return new Game(BoardFactory.createBoard(_sizeBoard), getWhitePlayer());
            
        }
    }


}
